#include "list.h"
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>

struct list* find(struct list* l,char c){
	while(l!=NULL){
		if(l->c==c)
			return l;
		l=l->next;
	}
	return NULL;
}
int listlen(struct list *l){
	int i=0;
	while(l!=NULL){
		i++;
		l=l->next;
	}
	return i;
}
struct list * reverse_list(struct list * head){
	struct list * before=NULL;
	while(head!=NULL && head->next!=NULL){
		struct list * next=head->next;
		head->next=before;
		before=head;
		head=next;
	}
	head->next=before;
	return head;
}

struct list * sort_list(struct list* head){
	assert(head!=NULL);
	
	struct list* pos;
	int i=listlen(head);
	for(;i>0;i--){
		struct list * inpos=head;
		struct list * before=NULL;
		while(inpos!=NULL && inpos->next!=NULL){
			if(inpos->weight > inpos->next->weight){
				if(inpos==head)
					head=inpos->next;
				if(before!=NULL){
					before->next=inpos->next;
				}
				before=inpos->next;
				struct list * a=inpos;
				struct list * b=inpos->next;
				struct list * tmp=inpos->next->next;
				inpos->next->next=a;
				a->next=tmp;
				inpos=a;
			}else{
				before=inpos;
				inpos=inpos->next;
				//printf("march %c\n",inpos->c);
			}
		}
		
	}
	return head;
}

void swap_list(struct list* a ,struct list* b){
	struct list * tmp=b->next;
	b->next=a;
	a->next=tmp;
}

void printList(struct list * head){
	struct list* pos=head;
	while(pos!=NULL){
		printf("%c,%d\n",pos->c,pos->weight);
		pos=pos->next;
	}
}